package com.orangelife.mobile.parkingcard.activity;

/**
 * 停车卡详情
 */

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.curry.android.http.HttpUtil;
import com.curry.android.http.OrangeDataHandler;
import com.curry.android.http.OrangeErrorHandler;
import com.curry.android.http.VolleyHttpUtil;
import com.curry.android.util.DialogHelper;
import com.curry.android.util.IntentHelper;
import com.curry.android.util.JSONHelper;
import com.curry.orangelife.mobile.R;
import com.google.gson.reflect.TypeToken;
import com.markupartist.android.widget.PullToRefreshListView;
import com.markupartist.android.widget.PullToRefreshListView.IXListViewListener;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.common.biz.JSONRequest;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.constants.ParkingCardURL;
import com.orangelife.mobile.parkingcard.adapter.ParkingCardDetailAdapter;
import com.orangelife.mobile.util.JsonReponseHandler;
import com.orangelife.mobile.util.ToastHelper;

import org.json.JSONObject;

public class ParkingCardDetailActivity extends OrangeLifeBaseActivity {

    /**
     * 尾部的view
     */
//	private View buttomView;

    /**
     * 有缴费-停车卡
     */
    private TextView tvParkingCard;
    /**
     * 有缴费-车牌号
     **/
    private TextView tvCarNumber;
    /**
     * 有缴费-停车场类型和钱
     **/
    private TextView tvTypeAndMoney;
    /**
     * 有缴费-有效期
     **/
    private TextView tvValidity;
    /**
     * 有缴费-累计缴费
     */
    private TextView tvMoney;
    /**
     * 标题
     */
    private TextView tvTitle;
    /**全局的relativelayout*/
//	private RelativeLayout rlAll;
    /**底部充值缴费*/
//	private LinearLayout llButtom;
    /**
     * 底部的textview
     */
    private TextView tvButtom;

    /**
     * 缴费数据
     */
    private PullToRefreshListView lvList;
    /**
     * 充值缴费按钮
     */
    private Button btnPayment;

    /**
     * 进度条
     */
    private Dialog dialog;
    private List<Map<String, Object>> list;
    private List<Map<String, Object>> list2;
    @SuppressWarnings("rawtypes")
    private ParkingCardDetailAdapter adapter;
    /**
     * 分辨是刷新还是加载更多
     */
    private int flags = 1;
    /**
     * 一页中数据的条数，初始设置为7条
     */
    private int pageSize = Constant.PAGE_SIZE_DEFAULLT;
    /**
     * 初始页，初始化为第一页
     */
    private int pageNo = Constant.PAGE_NO_DEFAULT;
    private Handler mHandler;
    /**
     * 停车卡
     */
    private String number = "";
    /**
     * 车牌号
     */
    private String carNumber = "";
    /**
     * 停车场类型
     */
    private String parkingType = "";
    /**
     * 有效期
     */
    private String valid_time = "";
    /**
     * 第三方停车卡id
     */
    private String cardsID = "";
    /**
     * 第三方停车终端ID
     */
    private String parkID = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_parking_card_detail);
        initeView();
        findView();
    }

    /**
     * 初始化
     */
    private void initeView() {
        tvTitle = (TextView) findViewById(R.id.tv_title);
        tvCarNumber = (TextView) findViewById(R.id.tvCarNumber);
        tvParkingCard = (TextView) findViewById(R.id.tvParkingCard);
        tvTypeAndMoney = (TextView) findViewById(R.id.tvTypeAndMoney);
        tvValidity = (TextView) findViewById(R.id.tvValidity);
        tvMoney = (TextView) findViewById(R.id.tvMoney);
//		llButtom = (LinearLayout) findViewById(R.id.llButtom);
        btnPayment = (Button) findViewById(R.id.btnPayment);
        lvList = (PullToRefreshListView) findViewById(R.id.lvList);
        tvButtom = (TextView) findViewById(R.id.tvButtom);
//		rlAll = (RelativeLayout) findViewById(R.id.rlAll);

    }


    /**
     * 赋值
     */
    private void findView() {
        tvTitle.setText("停车卡详情");
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        @SuppressWarnings("unchecked")
        Map<String, Object> mapL = (Map<String, Object>) bundle.getSerializable("map");
        //左边的设置值
        number = mapL.get("number").toString();
        carNumber = mapL.get("carNumber").toString();
        parkingType = mapL.get("parkingType").toString();
        valid_time = mapL.get("expiration_time").toString();
        cardsID = mapL.get("cardsID").toString();
        parkID = mapL.get("parkID").toString();
        mHandler = new Handler();
//		initeButtom();
        getData(pageSize, pageNo);
        setAdapter();
        lvList.setPullLoadEnable(false);
        pullListView();
        btnPayment.setOnClickListener(listener);
    }
//	
//	/**
//	 * 添加尾部的view
//	 */
//	private void initeButtom() {
//		
//		buttomView = getLayoutInflater().inflate(R.layout.item_parking_detail_buttom,null);
//		llButtom = (LinearLayout)buttomView.findViewById(R.id.llButtom);
//		btnPayment = (Button) buttomView.findViewById(R.id.btnPayment);
//		lvList.addFooterView(buttomView);
//	}

    /**
     * 设置适配器
     */
    private void setAdapter() {
        list = new ArrayList<Map<String, Object>>();
        list2 = new ArrayList<Map<String, Object>>();
        adapter = new ParkingCardDetailAdapter<Map<String, Object>>(this, list);
        lvList.setPullLoadEnable(false);
        lvList.setAdapter(adapter);
    }

    /**
     * 获取数据
     */
//	@SuppressWarnings("deprecation")
//	private void getData(int pageSize,int pageNo) {
//		showDialog(this);
//		Map<String,Object> map = new HashMap<String,Object>();
//		map.put("cardsID", cardsID);
//		map.put("pageSize", pageSize);
//		map.put("pageIndex", pageNo);
//		Map<String, Object> rootMap = new HashMap<String, Object>();
//		rootMap.put("map", map);
////		rootMap.put("url", Constant.URL_PARKCARD_PAY_MINE);
//		rootMap.put("url", ParkingCardURL.PARKCARD_PAY_MINE);
//		rootMap.put("wat", 1);
//
//		new JSONRequest(JSONRequest.GET, rootMap, handler, HttpUtil.ACTION_URI);
//	}
    @SuppressWarnings("deprecation")
    private void getData(int pageSize, int pageNo) {
        showDialog(this);
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("cardsID", cardsID);
        map.put("pageSize", String.valueOf(pageSize));
        map.put("pageIndex", String.valueOf(pageNo));

        VolleyHttpUtil.getInstance().getWithCallback(ParkingCardURL.PARKCARD_PAY_MINE, map, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject jsonObject, int i) {
                closeDialog();
                if (OrangeErrorHandler.getInstance().isSuccess(jsonObject)) {
                    list2 = OrangeDataHandler.getListFromJsonWithPageEntity(jsonObject, new TypeToken<List<Map<String, Object>>>() {
                    }.getType(), adapter, dialog);
                    updateListView(list2);
                    setDetail();
                }
            }
        });
    }

    private OnClickListener listener = new OnClickListener() {

        @Override
        public void onClick(View view) {

            switch (view.getId()) {
                case R.id.btnPayment:
                    //充值缴费
                    Bundle bundle = new Bundle();
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("carNumber", carNumber);
                    map.put("parkingType", parkingType);
                    map.put("parkID", parkID);
                    map.put("cardsID", cardsID);
                    IntentHelper.getInstances().bundleWithExtra(ParkingCardDetailActivity.this, ParkingCardFeeActivity.class, bundle, (Serializable) map);
                    finish();
                    break;

                default:
                    break;
            }
        }
    };

    /**
     * 下拉刷新列表
     */
    private void pullListView() {
        lvList.setXListViewListener(new IXListViewListener() {
            @Override
            public void onRefresh() {
                mHandler.postDelayed(new Runnable() {

                    @SuppressWarnings("unchecked")
                    @Override
                    public void run() {
                        // list.clear();
                        flags = 1;
                        pageNo = 1;
                        getData(pageSize, pageNo);
                        onLoad();
                        adapter.setList(list);
                        adapter.notifyDataSetChanged();
                    }
                }, 2000);
            }

            @Override
            public void onLoadMore() {
                mHandler.postDelayed(new Runnable() {
                    @SuppressWarnings("unchecked")
                    @Override
                    public void run() {
                        flags = 0;
                        pageNo += 1;
                        getData(pageSize, pageNo);
                        onLoad();
                        if (list != null) {
                            adapter.setList(list);
                            adapter.notifyDataSetChanged();
                        }
                    }
                }, 2000);
            }
        });
    }

    @SuppressWarnings("deprecation")
    private void onLoad() {
        lvList.stopRefresh();
        lvList.stopLoadMore();
        lvList.setRefreshTime(new Date().toLocaleString());
    }

    /**
     * 刷新 拉下列表
     *
     * @param list2
     */
    @SuppressWarnings({"unchecked"})
    private void updateListView(List<Map<String, Object>> list2) {

        if (list2 != null && list != null) {
            if (list2.size() == 0) {
                if (flags == 1) {
                    list.clear();
                    lvList.setPullLoadEnable(false);
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                } else {
                    lvList.setPullLoadEnable(false);
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                }
            } else {
                if (flags == 1) {
                    list.clear();
                    lvList.setPullLoadEnable(true);
                    list.addAll(list2);
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                } else {
                    lvList.setPullLoadEnable(true);
                    list.addAll(list2);
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                }
            }
        } else {
            lvList.setPullLoadEnable(false);
        }
    }

    /**
     * 处理获得的数据
     */
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {

        @SuppressWarnings("unchecked")
        @Override
        public void handleMessage(Message msg) {
            closeDialog();
            switch (msg.what) {
                case 1:
                    String errCode = JSONHelper.jsonToMap(msg.obj.toString())
                            .get("errCode").toString();
                    if (errCode.equals("0")) {
                        list2 = JsonReponseHandler.getListFromJson(
                                String.valueOf(msg.obj), adapter, dialog);

                        updateListView(list2);
                        setDetail();
                    }
                    break;
                case 500:
                    DialogHelper.closeDialog(dialog);
                    ToastHelper.getInstance()._toast(
                            msg.obj.toString());
                    break;
                case 1011:
                    isLogin(dialog);
                    break;

                default:
                    break;
            }
        }

    };

    /**
     * 设置详情值
     */
    private void setDetail() {
        if (list.size() == 0) {
            lvList.setVisibility(View.GONE);
            tvValidity.setText("待缴费");
            tvMoney.setText("0.0");
        } else {
            lvList.setVisibility(View.VISIBLE);
            tvValidity.setText(valid_time);
            tvMoney.setText("¥" + list.get(0).get("total").toString());
            tvButtom.setVisibility(View.GONE);
        }
        tvParkingCard.setText("停车卡：" + number);
        tvCarNumber.setText("车牌：" + carNumber);
        tvTypeAndMoney.setText(parkingType);


    }

}
